Is Unique

Is Unique: Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures?


In [136]:
import random

#STR = random.uniform(('a').encode('ascii'), int('Z'))
#print(ord('A'))
#print(ord('z'))
#lowercase = [ chr(char) for char in range(ord('a'), ord('z') + 1)]
#uppercase = [ chr(char) for char in range(ord('A'), ord('Z') + 1)]
#string_seed = lowercase + uppercase
#print(string_seed)

def gen_randstr():
    size = random.randint(0, 100)
    return "".join((random.choice(string_seed) for _ in range(size)))

random_string = gen_randstr()
print(random_string)


LAzLzB

In [137]:
def isUnique(input_string):
    marks = [False for _ in range(256)]
    for i in range(1, len(input_string)):
        char = ord(input_string[i])
        if marks[char] == True:
            print("not unique {} at {}".format(input_string[i], i))
            return False
        else:
            marks[char] = True
    return True

print(isUnique(random_string))


not unique z at 4
False

Check Permutation

Check Permutation: Given two strings, write a method to decide if one is a permutation of the other.


In [138]:
def str_shuffle(str):
    str_list = list(str)
    random.shuffle(str_list)
    return "".join(str_list)


str0 = gen_randstr()
str1 = gen_randstr()

str2 = gen_randstr()
str3 = str_shuffle(str2[:])
print(str2)
print(str3)


def check_permutation(str0, str1):
    str0_ = "".join(sorted(str0))
    str1_ = "".join(sorted(str1))
    print(str0_)
    print(str1_)
    if len(str0_) != len(str1_):
        return False
    
    for i in range(len(str0_)):
        if str0_[i] != str1_[i]:
            print(i)
            return False
        
    return True

print("Test#1: %s"%("Pass" if False == check_permutation(str0, str1) else "Fail"))
print("Test#2: %s"%("Pass" if True == check_permutation(str2, str3) else 'Fail'))


qogCOnRKIGrwRhdaXPsekfw
aIneCPgqOGwwXskrfKRRodh
BBDDDEEFFGHHHIJKLLMNPPPPPQQSSSTUUUUVVWXXZZabcceffgghhiiiijkkkpqqrtuuvvwwwwzz
AKkwy
Test#1: Pass
CGIKOPRRXadefghknoqrsww
CGIKOPRRXadefghknoqrsww
Test#2: Pass

Palindrome Permutation:

Given a string, write a function to check if it is a permutation of a palindrome. A palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words.


In [139]:
def check_palindrome(str0):
    size = len(str0)
    for i in range(size):
        if str0[i] != str0[size - 1 - i]:
            return False
    return True

str0 = "AAAABBBBAAAA"
str1 = "AAAAAAAAABBB"

print("Test#1: %s"%("Pass" if True == check_palindrome(str0) else "Fail"))
print("Test#2: %s"%("Pass" if False == check_palindrome(str1) else "Fail"))


Test#1: Pass
Test#2: Pass

Palindrome Permutation

Given a string, write a function to check if it is a permutation of a palindrome. A palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words.


In [140]:
def check_palindrome_permutation(str0):
    
    str0 = str0.lower()
    histogram = {}
    for ch in str0:
        if ch != ' ':
            histogram[ch] = histogram.get(ch, 0) + 1
            
    # check one odd entries
    found_odd = False
    for ch, value in histogram.items():
        if value%2 == 1:
            if found_odd:
                return False
            found_odd = True
            
    return True

print("Test#1: %s"%("Pass" if True == check_palindrome_permutation('Tact Coa') else "Fail"))
print("Test#2: %s"%("Pass" if False == check_palindrome_permutation('AAABBBCCC') else "Fail"))


Test#1: Pass
Test#2: Pass

One Away:

There are three types of edits that can be performed on strings: insert a character,remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away.


In [141]:
def check_same(str0, str1):
    if len(str0) != len(str1):
        return False
    for i in range(len(str0)):
        if str0[i] != str1[i]:
            return False
    return True

def check_oneaway(str0, str1):
        
    for i in range(len(str0)):
        if (i < len(str1) and str0[i] != str1[i]) or i > (len(str1) - 1):

            if check_same(str0[i + 1:], str1[i:]):
                # remove
                return True
            if check_same(str0[i:],str1[i + 1:]):
                # insert
                return True
            if check_same(str0[i+1:], str1[i+1:]):
                # replace
                return True
            return False
    return False


print("Test#1: %s"%("Pass" if True == check_oneaway("pale", "ple") else "Fail"))
print("Test#2: %s"%("Pass" if True == check_oneaway("pales", "pale") else "Fail"))
print("Test#3: %s"%("Pass" if True == check_oneaway("pale", "bale") else "Fail"))
print("Test#4: %s"%("Pass" if False == check_oneaway("pale", "bake") else "Fail"))
print("Test#4: %s"%("Pass" if False == check_oneaway("AAAAABBBBBBBBB", "AAAAABBBB") else "Fail"))


Test#1: Pass
Test#2: Pass
Test#3: Pass
Test#4: Pass
Test#4: Pass

String Compression:

Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2b1c5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (a - z).


In [142]:
def _string_compression(str0):
    dest = ""
    cur_ch = str0[0]
    count = 0
    for i in range(len(str0)):
        if cur_ch == str0[i]:
            count += 1
        else:
            dest += cur_ch
            dest += str(count)
            cur_ch = str0[i]
            count = 1
    dest += cur_ch
    dest += str(count)
    cur_ch = str0[i]
    count = 0


    return dest
     
def string_compression(str0):
    str_ = _string_compression(str0)
    if len(str_) < len(str0):
        return str_
    else:
        return str0
print("Test#1: %s"%("Pass" if "A4B5C3" == string_compression("AAAABBBBBCCC") else "Fail"))
print("Test#2: %s"%("Pass" if "ABCDEF" == string_compression("ABCDEF") else "Fail"))
print("Test#3: %s"%("Pass" if "a2b1c5a3" == string_compression("aabcccccaaa") else "Fail"))


Test#1: Pass
Test#2: Pass
Test#3: Pass

Rotate Matrix:

Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?


In [ ]:

Zero Matrix:

Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0.


In [143]:
import numpy as np

matrix = np.random.randint(0, 20, (10,10))
print(matrix)

def set_matrix_zero(mat):
    
    zero_rows = []
    zero_cols = []
    h, w = mat.shape
    for i in range(h):
        for j in range(w):
            if mat[i][j] == 0:
                zero_rows.append(i)
                zero_cols.append(j)
                
    for row in zero_rows:
        mat[row, :] = 0
    for col in zero_cols:
        mat[:, col] = 0
        
    return mat

print(set_matrix_zero(matrix))


[[16  5 18  5 16  8 17 10 13 14]
 [10  6  2  2  1 13 19  3 11  2]
 [15 16  1  4  2 15  9  7  7  7]
 [ 3 13  6 10 10 15 16  3 13  8]
 [14  5  0 18  6 17 14  3 18 16]
 [18  2  7 16  4 18 12 15 18 11]
 [ 3  0 19  7  1  4  9 19  3  7]
 [ 2  8 16 17  5  5  9 11  9  7]
 [18 19  0 15  3  5  6 17  1  8]
 [15 12 14 13 11  1 14 13  2 12]]
[[16  0  0  5 16  8 17 10 13 14]
 [10  0  0  2  1 13 19  3 11  2]
 [15  0  0  4  2 15  9  7  7  7]
 [ 3  0  0 10 10 15 16  3 13  8]
 [ 0  0  0  0  0  0  0  0  0  0]
 [18  0  0 16  4 18 12 15 18 11]
 [ 0  0  0  0  0  0  0  0  0  0]
 [ 2  0  0 17  5  5  9 11  9  7]
 [ 0  0  0  0  0  0  0  0  0  0]
 [15  0  0 13 11  1 14 13  2 12]]

In [ ]: